﻿using B.S.DataBase.MyProject.Domain.SalesReports;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using MediatR;
using T.E.ERP.Read.API.Applicantions.Command.Kanbans;

namespace T.E.ERP.Read.API.Applicantions.CommandHandler.KanbanHandler
{
    public class TemplateHandler4 : IRequestHandler<TemplateCommand4, APIResult<List<MaterialInOutDto>>>
    {
        private readonly IBaseRepository<SalesReturns> _salesReturns;

        public TemplateHandler4(IBaseRepository<SalesReturns> salesReturns)
        {
            _salesReturns = salesReturns;
        }

        public async Task<APIResult<List<MaterialInOutDto>>> Handle(TemplateCommand4 request, CancellationToken cancellationToken)
        {
            var result = new APIResult<List<MaterialInOutDto>>()
            {
                Code = APIEnum.查询成功,
                Msg = APIEnum.查询成功.ToString(),
            };
            var query = (await _salesReturns.GetAll()).AsQueryable();
            // 投影到DTO
            var materials = query
                .Select(x => new MaterialInOutDto
                {
                    ClientName = x.ClientName,
                    ReturnNum = x.ReturnNum,
                    RuNum = x.RuNum,
                    WuliaoName=x.WuliaoName
                });

            // 应用数量限制
            if (request.TopN.HasValue && request.TopN > 0)
            {
                materials = materials.Take(request.TopN.Value);
            }
            result.data = materials.ToList();

            return await Task.FromResult(result);
        }
    }
}
